<!DOCTYPE html><html lang="zh-CN" data-theme="light"><head><meta charset="UTF-8"><meta http-equiv="X-UA-Compatible" content="IE=edge"><meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0"><title>Kotlin编程第一课--(协程篇)17  Context：万物皆为Context？ | 码行</title><meta name="author" content="Carl Su"><meta name="copyright" content="Carl Su"><meta name="format-detection" content="telephone=no"><meta name="theme-color" content="ffffff"><meta name="description" content="今天我们来学习 Kotlin 协程的 Context。 协程的 Context，在 Kotlin 当中有一个具体的名字，叫做 CoroutineContext。它是我们理解 Kotlin 协程非常关键的一环。 从概念上讲，CoroutineContext 很容易理解，它只是个上下文而已，实际开发中它最常见的用处就是切换线程池。不过，CoroutineContext 背后的代码设计其实比较复杂，如果">
<meta property="og:type" content="article">
<meta property="og:title" content="Kotlin编程第一课--(协程篇)17  Context：万物皆为Context？">
<meta property="og:url" content="https://devsu.top/posts/12ca5097/index.html">
<meta property="og:site_name" content="码行">
<meta property="og:description" content="今天我们来学习 Kotlin 协程的 Context。 协程的 Context，在 Kotlin 当中有一个具体的名字，叫做 CoroutineContext。它是我们理解 Kotlin 协程非常关键的一环。 从概念上讲，CoroutineContext 很容易理解，它只是个上下文而已，实际开发中它最常见的用处就是切换线程池。不过，CoroutineContext 背后的代码设计其实比较复杂，如果">
<meta property="og:locale" content="zh_CN">
<meta property="og:image" content="https://img2.baidu.com/it/u=3107178066,1951512797&fm=253&fmt=auto&app=138&f=JPEG?w=704&h=500">
<meta property="article:published_time" content="2022-05-25T01:51:38.000Z">
<meta property="article:modified_time" content="2023-03-23T07:55:59.545Z">
<meta property="article:author" content="Carl Su">
<meta property="article:tag" content="Kotlin">
<meta name="twitter:card" content="summary">
<meta name="twitter:image" content="https://img2.baidu.com/it/u=3107178066,1951512797&fm=253&fmt=auto&app=138&f=JPEG?w=704&h=500"><link rel="shortcut icon" href="https://s2.loli.net/2023/03/09/whMHdYkrKoIBnSC.png"><link rel="canonical" href="https://devsu.top/posts/12ca5097/index.html"><link rel="preconnect" href="//cdn.jsdelivr.net"/><link rel="preconnect" href="//hm.baidu.com"/><link rel="preconnect" href="//busuanzi.ibruce.info"/><link rel="stylesheet" href="/css/index.css"><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@fortawesome/fontawesome-free/css/all.min.css" media="print" onload="this.media='all'"><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/node-snackbar/dist/snackbar.min.css" media="print" onload="this.media='all'"><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@fancyapps/ui/dist/fancybox.min.css" media="print" onload="this.media='all'"><script>var _hmt = _hmt || [];
(function() {
  var hm = document.createElement("script");
  hm.src = "https://hm.baidu.com/hm.js?6243425e2ecb037931274c4ca1db3132";
  var s = document.getElementsByTagName("script")[0]; 
  s.parentNode.insertBefore(hm, s);
})();
</script><script>const GLOBAL_CONFIG = { 
  root: '/',
  algolia: undefined,
  localSearch: {"path":"/search.xml","preload":true,"languages":{"hits_empty":"找不到您查询的内容：${query}"}},
  translate: {"defaultEncoding":2,"translateDelay":0,"msgToTraditionalChinese":"繁","msgToSimplifiedChinese":"简"},
  noticeOutdate: undefined,
  highlight: {"plugin":"highlighjs","highlightCopy":true,"highlightLang":true,"highlightHeightLimit":300},
  copy: {
    success: '复制成功',
    error: '复制错误',
    noSupport: '浏览器不支持'
  },
  relativeDate: {
    homepage: false,
    post: false
  },
  runtime: '天',
  date_suffix: {
    just: '刚刚',
    min: '分钟前',
    hour: '小时前',
    day: '天前',
    month: '个月前'
  },
  copyright: {"limitCount":50,"languages":{"author":"作者: Carl Su","link":"链接: ","source":"来源: 码行","info":"著作权归作者所有。商业转载请联系作者获得授权，非商业转载请注明出处。"}},
  lightbox: 'fancybox',
  Snackbar: {"chs_to_cht":"你已切换为繁体","cht_to_chs":"你已切换为简体","day_to_night":"你已切换为深色模式","night_to_day":"你已切换为浅色模式","bgLight":"#49b1f5","bgDark":"#1f1f1f","position":"bottom-left"},
  source: {
    justifiedGallery: {
      js: 'https://cdn.jsdelivr.net/npm/flickr-justified-gallery/dist/fjGallery.min.js',
      css: 'https://cdn.jsdelivr.net/npm/flickr-justified-gallery/dist/fjGallery.min.css'
    }
  },
  isPhotoFigcaption: true,
  islazyload: true,
  isAnchor: false,
  percent: {
    toc: true,
    rightside: true,
  }
}</script><script id="config-diff">var GLOBAL_CONFIG_SITE = {
  title: 'Kotlin编程第一课--(协程篇)17  Context：万物皆为Context？',
  isPost: true,
  isHome: false,
  isHighlightShrink: false,
  isToc: true,
  postUpdate: '2023-03-23 15:55:59'
}</script><noscript><style type="text/css">
  #nav {
    opacity: 1
  }
  .justified-gallery img {
    opacity: 1
  }

  #recent-posts time,
  #post-meta time {
    display: inline !important
  }
</style></noscript><script>(win=>{
    win.saveToLocal = {
      set: function setWithExpiry(key, value, ttl) {
        if (ttl === 0) return
        const now = new Date()
        const expiryDay = ttl * 86400000
        const item = {
          value: value,
          expiry: now.getTime() + expiryDay,
        }
        localStorage.setItem(key, JSON.stringify(item))
      },

      get: function getWithExpiry(key) {
        const itemStr = localStorage.getItem(key)

        if (!itemStr) {
          return undefined
        }
        const item = JSON.parse(itemStr)
        const now = new Date()

        if (now.getTime() > item.expiry) {
          localStorage.removeItem(key)
          return undefined
        }
        return item.value
      }
    }
  
    win.getScript = url => new Promise((resolve, reject) => {
      const script = document.createElement('script')
      script.src = url
      script.async = true
      script.onerror = reject
      script.onload = script.onreadystatechange = function() {
        const loadState = this.readyState
        if (loadState && loadState !== 'loaded' && loadState !== 'complete') return
        script.onload = script.onreadystatechange = null
        resolve()
      }
      document.head.appendChild(script)
    })
  
    win.getCSS = (url,id = false) => new Promise((resolve, reject) => {
      const link = document.createElement('link')
      link.rel = 'stylesheet'
      link.href = url
      if (id) link.id = id
      link.onerror = reject
      link.onload = link.onreadystatechange = function() {
        const loadState = this.readyState
        if (loadState && loadState !== 'loaded' && loadState !== 'complete') return
        link.onload = link.onreadystatechange = null
        resolve()
      }
      document.head.appendChild(link)
    })
  
      win.activateDarkMode = function () {
        document.documentElement.setAttribute('data-theme', 'dark')
        if (document.querySelector('meta[name="theme-color"]') !== null) {
          document.querySelector('meta[name="theme-color"]').setAttribute('content', '#0d0d0d')
        }
      }
      win.activateLightMode = function () {
        document.documentElement.setAttribute('data-theme', 'light')
        if (document.querySelector('meta[name="theme-color"]') !== null) {
          document.querySelector('meta[name="theme-color"]').setAttribute('content', 'ffffff')
        }
      }
      const t = saveToLocal.get('theme')
    
          const now = new Date()
          const hour = now.getHours()
          const isNight = hour <= 6 || hour >= 18
          if (t === undefined) isNight ? activateDarkMode() : activateLightMode()
          else if (t === 'light') activateLightMode()
          else activateDarkMode()
        
      const asideStatus = saveToLocal.get('aside-status')
      if (asideStatus !== undefined) {
        if (asideStatus === 'hide') {
          document.documentElement.classList.add('hide-aside')
        } else {
          document.documentElement.classList.remove('hide-aside')
        }
      }
    
    const detectApple = () => {
      if(/iPad|iPhone|iPod|Macintosh/.test(navigator.userAgent)){
        document.documentElement.classList.add('apple')
      }
    }
    detectApple()
    })(window)</script><meta name="generator" content="Hexo 6.3.0"></head><body><div id="loading-box"><div class="loading-left-bg"></div><div class="loading-right-bg"></div><div class="spinner-box"><div class="configure-border-1"><div class="configure-core"></div></div><div class="configure-border-2"><div class="configure-core"></div></div><div class="loading-word">加载中...</div></div></div><script>const preloader = {
  endLoading: () => {
    document.body.style.overflow = 'auto';
    document.getElementById('loading-box').classList.add("loaded")
  },
  initLoading: () => {
    document.body.style.overflow = '';
    document.getElementById('loading-box').classList.remove("loaded")

  }
}
window.addEventListener('load',()=> { preloader.endLoading() })

if (false) {
  document.addEventListener('pjax:send', () => { preloader.initLoading() })
  document.addEventListener('pjax:complete', () => { preloader.endLoading() })
}</script><div id="sidebar"><div id="menu-mask"></div><div id="sidebar-menus"><div class="avatar-img is-center"><img src="https://s2.loli.net/2023/03/09/QrI9mgJ4XlbEPzN.png" onerror="onerror=null;src='/img/friend_404.gif'" alt="avatar"/></div><div class="sidebar-site-data site-data is-center"><a href="/archives/"><div class="headline">文章</div><div class="length-num">169</div></a><a href="/tags/"><div class="headline">标签</div><div class="length-num">37</div></a><a href="/categories/"><div class="headline">分类</div><div class="length-num">38</div></a></div><hr/><div class="menus_items"><div class="menus_item"><a class="site-page" href="/"><i class="fa-fw fas fa-home"></i><span> 首页</span></a></div><div class="menus_item"><a class="site-page" href="/archives/"><i class="fa-fw fas fa-archive"></i><span> 时间轴</span></a></div><div class="menus_item"><a class="site-page" href="/archives/"><i class="fa-fw fas fa-archive"></i><span> 归档</span></a></div><div class="menus_item"><a class="site-page" href="/tags/"><i class="fa-fw fas fa-tags"></i><span> 标签</span></a></div><div class="menus_item"><a class="site-page" href="/categories/"><i class="fa-fw fas fa-folder-open"></i><span> 分类</span></a></div><div class="menus_item"><a class="site-page group" href="javascript:void(0);"><i class="fa-fw fas fa-list"></i><span> 清单</span><i class="fas fa-chevron-down"></i></a><ul class="menus_item_child"><li><a class="site-page child" href="/music/"><i class="fa-fw fas fa-music"></i><span> 音乐</span></a></li><li><a class="site-page child" href="/Gallery/"><i class="fa-fw fas fa-images"></i><span> 照片</span></a></li><li><a class="site-page child" href="/movies/"><i class="fa-fw fas fa-video"></i><span> 电影</span></a></li></ul></div><div class="menus_item"><a class="site-page" href="/link/"><i class="fa-fw fas fa-link"></i><span> 友链</span></a></div><div class="menus_item"><a class="site-page" href="/about/"><i class="fa-fw fas fa-heart"></i><span> 关于</span></a></div></div></div></div><div class="post" id="body-wrap"><header class="post-bg fixed" id="page-header" style="background-image: url('https://img2.baidu.com/it/u=3107178066,1951512797&amp;fm=253&amp;fmt=auto&amp;app=138&amp;f=JPEG?w=704&amp;h=500')"><nav id="nav"><span id="blog-info"><a href="/" title="码行"><img class="site-icon" src="https://s2.loli.net/2023/03/09/whMHdYkrKoIBnSC.png"/><span class="site-name">码行</span></a></span><div id="menus"><div id="search-button"><a class="site-page social-icon search" href="javascript:void(0);"><i class="fas fa-search fa-fw"></i><span> 搜索</span></a></div><div class="menus_items"><div class="menus_item"><a class="site-page" href="/"><i class="fa-fw fas fa-home"></i><span> 首页</span></a></div><div class="menus_item"><a class="site-page" href="/archives/"><i class="fa-fw fas fa-archive"></i><span> 时间轴</span></a></div><div class="menus_item"><a class="site-page" href="/archives/"><i class="fa-fw fas fa-archive"></i><span> 归档</span></a></div><div class="menus_item"><a class="site-page" href="/tags/"><i class="fa-fw fas fa-tags"></i><span> 标签</span></a></div><div class="menus_item"><a class="site-page" href="/categories/"><i class="fa-fw fas fa-folder-open"></i><span> 分类</span></a></div><div class="menus_item"><a class="site-page group" href="javascript:void(0);"><i class="fa-fw fas fa-list"></i><span> 清单</span><i class="fas fa-chevron-down"></i></a><ul class="menus_item_child"><li><a class="site-page child" href="/music/"><i class="fa-fw fas fa-music"></i><span> 音乐</span></a></li><li><a class="site-page child" href="/Gallery/"><i class="fa-fw fas fa-images"></i><span> 照片</span></a></li><li><a class="site-page child" href="/movies/"><i class="fa-fw fas fa-video"></i><span> 电影</span></a></li></ul></div><div class="menus_item"><a class="site-page" href="/link/"><i class="fa-fw fas fa-link"></i><span> 友链</span></a></div><div class="menus_item"><a class="site-page" href="/about/"><i class="fa-fw fas fa-heart"></i><span> 关于</span></a></div></div><div id="toggle-menu"><a class="site-page" href="javascript:void(0);"><i class="fas fa-bars fa-fw"></i></a></div></div></nav><div id="post-info"><h1 class="post-title">Kotlin编程第一课--(协程篇)17  Context：万物皆为Context？</h1><div id="post-meta"><div class="meta-firstline"><span class="post-meta-date"><i class="far fa-calendar-alt fa-fw post-meta-icon"></i><span class="post-meta-label">发表于</span><time class="post-meta-date-created" datetime="2022-05-25T01:51:38.000Z" title="发表于 2022-05-25 09:51:38">2022-05-25</time><span class="post-meta-separator">|</span><i class="fas fa-history fa-fw post-meta-icon"></i><span class="post-meta-label">更新于</span><time class="post-meta-date-updated" datetime="2023-03-23T07:55:59.545Z" title="更新于 2023-03-23 15:55:59">2023-03-23</time></span><span class="post-meta-categories"><span class="post-meta-separator">|</span><i class="fas fa-inbox fa-fw post-meta-icon"></i><a class="post-meta-categories" href="/categories/Android/">Android</a><i class="fas fa-angle-right post-meta-separator"></i><i class="fas fa-inbox fa-fw post-meta-icon"></i><a class="post-meta-categories" href="/categories/Android/Kotlin/">Kotlin</a><i class="fas fa-angle-right post-meta-separator"></i><i class="fas fa-inbox fa-fw post-meta-icon"></i><a class="post-meta-categories" href="/categories/Android/Kotlin/Kotlin%E7%BC%96%E7%A8%8B%E7%AC%AC%E4%B8%80%E8%AF%BE/">Kotlin编程第一课</a></span></div><div class="meta-secondline"><span class="post-meta-separator">|</span><span class="post-meta-wordcount"><i class="far fa-file-word fa-fw post-meta-icon"></i><span class="post-meta-label">字数总计:</span><span class="word-count">4.4k</span><span class="post-meta-separator">|</span><i class="far fa-clock fa-fw post-meta-icon"></i><span class="post-meta-label">阅读时长:</span><span>16分钟</span></span><span class="post-meta-separator">|</span><span class="post-meta-pv-cv" id="" data-flag-title="Kotlin编程第一课--(协程篇)17  Context：万物皆为Context？"><i class="far fa-eye fa-fw post-meta-icon"></i><span class="post-meta-label">阅读量:</span><span id="busuanzi_value_page_pv"><i class="fa-solid fa-spinner fa-spin"></i></span></span></div></div></div></header><main class="layout" id="content-inner"><div id="post"><article class="post-content" id="article-container"><p>今天我们来学习 Kotlin 协程的 Context。</p>
<p>协程的 Context，在 Kotlin 当中有一个具体的名字，叫做 CoroutineContext。它是我们理解 Kotlin 协程非常关键的一环。</p>
<p>从概念上讲，CoroutineContext 很容易理解，它只是个上下文而已，实际开发中它最常见的用处就是切换线程池。不过，CoroutineContext 背后的代码设计其实比较复杂，如果不能深入理解它的设计思想，那我们在后面阅读协程源码，并进一步建立复杂并发结构的时候，都将会困难重重。</p>
<p>所以这节课，我将会从应用的角度出发，带你了解 CoroutineContext 的使用场景，并会对照源码带你理解它的设计思路。另外，知识点之间的串联也是很重要的，所以我还会带你分析它跟我们前面学的 Job、Deferred、launch、async 有什么联系，让你能真正理解和掌握协程的上下文，<strong>并建立一个基于 CoroutineContext 的协程知识体系</strong>。</p>
<h2 id="Context-的应用"><a href="#Context-的应用" class="headerlink" title="Context 的应用"></a>Context 的应用</h2><p>前面说过，CoroutineContext 就是协程的上下文。你在前面的第 14~16 讲里其实就已经见过它了。在第 14 讲我介绍 launch 源码的时候，CoroutineContext 其实就是函数的第一个参数：</p>
<figure class="highlight kotlin"><table><tr><td class="code"><pre><span class="line"></span><br><span class="line"><span class="comment">// 代码段1</span></span><br><span class="line"></span><br><span class="line"><span class="keyword">public</span> <span class="function"><span class="keyword">fun</span> CoroutineScope.<span class="title">launch</span><span class="params">(</span></span></span><br><span class="line"><span class="params"><span class="function"><span class="comment">//                这里</span></span></span></span><br><span class="line"><span class="params"><span class="function"><span class="comment">//                 ↓</span></span></span></span><br><span class="line"><span class="params"><span class="function">    context: <span class="type">CoroutineContext</span> = EmptyCoroutineContext,</span></span></span><br><span class="line"><span class="params"><span class="function">    start: <span class="type">CoroutineStart</span> = CoroutineStart.DEFAULT,</span></span></span><br><span class="line"><span class="params"><span class="function">    block: <span class="type">suspend</span> <span class="type">CoroutineScope</span>.() -&gt; <span class="type">Unit</span></span></span></span><br><span class="line"><span class="params"><span class="function">)</span></span>: Job &#123;&#125;</span><br></pre></td></tr></table></figure>

<p>这里我先说一下，之前我们在调用 launch 的时候，都没有传 context 这个参数，因此它会使用默认值 EmptyCoroutineContext，顾名思义，这就是一个空的上下文对象。而如果我们想要指定 launch 工作的线程池的话，就需要自己传 context 这个参数了。</p>
<p>另外，在第 15 讲里，我们在挂起函数 getUserInfo() 当中，也用到了 withContext() 这个函数，当时我们传入的是“Dispatchers.IO”，这就是 Kotlin 官方提供的一个 CoroutineContext 对象。让我们来回顾一下：</p>
<figure class="highlight kotlin"><table><tr><td class="code"><pre><span class="line"></span><br><span class="line"><span class="comment">// 代码段2</span></span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">fun</span> <span class="title">main</span><span class="params">()</span></span> = runBlocking &#123;</span><br><span class="line">    <span class="keyword">val</span> user = getUserInfo()</span><br><span class="line">    logX(user)</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="keyword">suspend</span> <span class="function"><span class="keyword">fun</span> <span class="title">getUserInfo</span><span class="params">()</span></span>: String &#123;</span><br><span class="line">    logX(<span class="string">&quot;Before IO Context.&quot;</span>)</span><br><span class="line">    withContext(Dispatchers.IO) &#123;</span><br><span class="line">        logX(<span class="string">&quot;In IO Context.&quot;</span>)</span><br><span class="line">        delay(<span class="number">1000L</span>)</span><br><span class="line">    &#125;</span><br><span class="line">    logX(<span class="string">&quot;After IO Context.&quot;</span>)</span><br><span class="line">    <span class="keyword">return</span> <span class="string">&quot;BoyCoder&quot;</span></span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">/*</span></span><br><span class="line"><span class="comment">输出结果：</span></span><br><span class="line"><span class="comment">================================</span></span><br><span class="line"><span class="comment">Before IO Context.</span></span><br><span class="line"><span class="comment">Thread:main @coroutine#1</span></span><br><span class="line"><span class="comment">================================</span></span><br><span class="line"><span class="comment">================================</span></span><br><span class="line"><span class="comment">In IO Context.</span></span><br><span class="line"><span class="comment">Thread:DefaultDispatcher-worker-1 @coroutine#1</span></span><br><span class="line"><span class="comment">================================</span></span><br><span class="line"><span class="comment">================================</span></span><br><span class="line"><span class="comment">After IO Context.</span></span><br><span class="line"><span class="comment">Thread:main @coroutine#1</span></span><br><span class="line"><span class="comment">================================</span></span><br><span class="line"><span class="comment">================================</span></span><br><span class="line"><span class="comment">BoyCoder</span></span><br><span class="line"><span class="comment">Thread:main @coroutine#1</span></span><br><span class="line"><span class="comment">================================</span></span><br><span class="line"><span class="comment">*/</span></span><br></pre></td></tr></table></figure>

<p>可以看到，当我们在 withContext() 这里指定线程池以后，Lambda 当中的代码就会被分发到 DefaultDispatcher 线程池中去执行，而它外部的所有代码仍然还是运行在 main 之上。</p>
<p>其实，Kotlin 官方还提供了挂起函数版本的 main() 函数，所以我们的代码也可以改成这样：</p>
<figure class="highlight kotlin"><table><tr><td class="code"><pre><span class="line"></span><br><span class="line"><span class="comment">// 代码段3</span></span><br><span class="line"></span><br><span class="line"><span class="keyword">suspend</span> <span class="function"><span class="keyword">fun</span> <span class="title">main</span><span class="params">()</span></span> &#123;</span><br><span class="line">    <span class="keyword">val</span> user = getUserInfo()</span><br><span class="line">    logX(user)</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>不过，你要注意的是：挂起函数版本的 main() 的底层做了很多封装，虽然它可以帮我们省去写 runBlocking 的麻烦，但不利于我们学习阶段的探索和研究。因此，后续的 Demo 我们仍然以 runBlocking 为主，你只需要知道 Kotlin 有这么一个东西，等到你深入理解协程以后，就可以直接用“suspend main()”写 Demo 了。</p>
<p>我们说回 runBlocking 这个函数，第 14 讲里我们介绍过，它的第一个参数也是 CoroutineContext，所以，我们也可以传入一个 Dispatcher 对象作为参数：</p>
<figure class="highlight kotlin"><table><tr><td class="code"><pre><span class="line"></span><br><span class="line"><span class="comment">// 代码段4</span></span><br><span class="line"></span><br><span class="line"><span class="comment">//                          变化在这里</span></span><br><span class="line"><span class="comment">//                             ↓</span></span><br><span class="line"><span class="function"><span class="keyword">fun</span> <span class="title">main</span><span class="params">()</span></span> = runBlocking(Dispatchers.IO) &#123;</span><br><span class="line">    <span class="keyword">val</span> user = getUserInfo()</span><br><span class="line">    logX(user)</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">/*</span></span><br><span class="line"><span class="comment">输出结果：</span></span><br><span class="line"><span class="comment">================================</span></span><br><span class="line"><span class="comment">Before IO Context.</span></span><br><span class="line"><span class="comment">Thread:DefaultDispatcher-worker-1 @coroutine#1</span></span><br><span class="line"><span class="comment">================================</span></span><br><span class="line"><span class="comment">================================</span></span><br><span class="line"><span class="comment">In IO Context.</span></span><br><span class="line"><span class="comment">Thread:DefaultDispatcher-worker-1 @coroutine#1</span></span><br><span class="line"><span class="comment">================================</span></span><br><span class="line"><span class="comment">================================</span></span><br><span class="line"><span class="comment">After IO Context.</span></span><br><span class="line"><span class="comment">Thread:DefaultDispatcher-worker-1 @coroutine#1</span></span><br><span class="line"><span class="comment">================================</span></span><br><span class="line"><span class="comment">================================</span></span><br><span class="line"><span class="comment">BoyCoder</span></span><br><span class="line"><span class="comment">Thread:DefaultDispatcher-worker-1 @coroutine#1</span></span><br><span class="line"><span class="comment">================================</span></span><br><span class="line"><span class="comment">*/</span></span><br></pre></td></tr></table></figure>

<p>这时候，我们会发现，所有的代码都运行在 DefaultDispatcher 这个线程池当中了。而 Kotlin 官方除了提供了 Dispatchers.IO 以外，还提供了 Dispatchers.Main、Dispatchers.Unconfined、Dispatchers.Default 这几种内置 Dispatcher。我来分别给你介绍一下：</p>
<ul>
<li><strong>Dispatchers.Main</strong>，它只在 UI 编程平台才有意义，在 Android、Swing 之类的平台上，一般只有 Main 线程才能用于 UI 绘制。这个 Dispatcher 在普通的 JVM 工程当中，是无法直接使用的。</li>
<li><strong>Dispatchers.Unconfined</strong>，代表无所谓，当前协程可能运行在任意线程之上。</li>
<li><strong>Dispatchers.Default</strong>，它是用于 CPU 密集型任务的线程池。一般来说，它内部的线程个数是与机器 CPU 核心数量保持一致的，不过它有一个最小限制 2。</li>
<li><strong>Dispatchers.IO</strong>，它是用于 IO 密集型任务的线程池。它内部的线程数量一般会更多一些（比如 64 个），具体线程的数量我们可以通过参数来配置：kotlinx.coroutines.io.parallelism。</li>
</ul>
<p>需要特别注意的是，Dispatchers.IO 底层是可能复用 Dispatchers.Default 当中的线程的。如果你足够细心的话，会发现前面我们用的都是 Dispatchers.IO，但实际运行的线程却是 DefaultDispatcher 这个线程池。</p>
<p>为了让这个问题更加清晰，我们可以把上面的例子再改一下：</p>
<figure class="highlight kotlin"><table><tr><td class="code"><pre><span class="line"></span><br><span class="line"><span class="comment">// 代码段5</span></span><br><span class="line"></span><br><span class="line"><span class="comment">//                          变化在这里</span></span><br><span class="line"><span class="comment">//                             ↓</span></span><br><span class="line"><span class="function"><span class="keyword">fun</span> <span class="title">main</span><span class="params">()</span></span> = runBlocking(Dispatchers.Default) &#123;</span><br><span class="line">    <span class="keyword">val</span> user = getUserInfo()</span><br><span class="line">    logX(user)</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">/*</span></span><br><span class="line"><span class="comment">输出结果：</span></span><br><span class="line"><span class="comment">================================</span></span><br><span class="line"><span class="comment">Before IO Context.</span></span><br><span class="line"><span class="comment">Thread:DefaultDispatcher-worker-1 @coroutine#1</span></span><br><span class="line"><span class="comment">================================</span></span><br><span class="line"><span class="comment">================================</span></span><br><span class="line"><span class="comment">In IO Context.</span></span><br><span class="line"><span class="comment">Thread:DefaultDispatcher-worker-2 @coroutine#1</span></span><br><span class="line"><span class="comment">================================</span></span><br><span class="line"><span class="comment">================================</span></span><br><span class="line"><span class="comment">After IO Context.</span></span><br><span class="line"><span class="comment">Thread:DefaultDispatcher-worker-2 @coroutine#1</span></span><br><span class="line"><span class="comment">================================</span></span><br><span class="line"><span class="comment">================================</span></span><br><span class="line"><span class="comment">BoyCoder</span></span><br><span class="line"><span class="comment">Thread:DefaultDispatcher-worker-2 @coroutine#1</span></span><br><span class="line"><span class="comment">================================</span></span><br><span class="line"><span class="comment">*/</span></span><br></pre></td></tr></table></figure>

<p><em><strong>当 Dispatchers.Default 线程池当中有富余线程的时候，它是可以被 IO 线程池复用的</strong></em>。可以看到，后面三个结果的输出都是在同一个线程之上的，这就是因为 Dispatchers.Default 被 Dispatchers.IO 复用线程导致的。如果我们换成自定义的 Dispatcher，结果就会不一样了。</p>
<figure class="highlight kotlin"><table><tr><td class="code"><pre><span class="line"></span><br><span class="line"><span class="comment">// 代码段6</span></span><br><span class="line"></span><br><span class="line"><span class="keyword">val</span> mySingleDispatcher = Executors.newSingleThreadExecutor &#123;</span><br><span class="line">    Thread(it, <span class="string">&quot;MySingleThread&quot;</span>).apply &#123; isDaemon = <span class="literal">true</span> &#125;</span><br><span class="line">&#125;.asCoroutineDispatcher()</span><br><span class="line"></span><br><span class="line"><span class="comment">//                          变化在这里</span></span><br><span class="line"><span class="comment">//                             ↓</span></span><br><span class="line"><span class="function"><span class="keyword">fun</span> <span class="title">main</span><span class="params">()</span></span> = runBlocking(mySingleDispatcher) &#123;</span><br><span class="line">    <span class="keyword">val</span> user = getUserInfo()</span><br><span class="line">    logX(user)</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="keyword">public</span> <span class="function"><span class="keyword">fun</span> ExecutorService.<span class="title">asCoroutineDispatcher</span><span class="params">()</span></span>: ExecutorCoroutineDispatcher =</span><br><span class="line">    ExecutorCoroutineDispatcherImpl(<span class="keyword">this</span>)</span><br><span class="line"></span><br><span class="line"><span class="comment">/*</span></span><br><span class="line"><span class="comment">输出结果：</span></span><br><span class="line"><span class="comment">================================</span></span><br><span class="line"><span class="comment">Before IO Context.</span></span><br><span class="line"><span class="comment">Thread:MySingleThread @coroutine#1</span></span><br><span class="line"><span class="comment">================================</span></span><br><span class="line"><span class="comment">================================</span></span><br><span class="line"><span class="comment">In IO Context.</span></span><br><span class="line"><span class="comment">Thread:DefaultDispatcher-worker-1 @coroutine#1</span></span><br><span class="line"><span class="comment">================================</span></span><br><span class="line"><span class="comment">================================</span></span><br><span class="line"><span class="comment">After IO Context.</span></span><br><span class="line"><span class="comment">Thread:MySingleThread @coroutine#1</span></span><br><span class="line"><span class="comment">================================</span></span><br><span class="line"><span class="comment">================================</span></span><br><span class="line"><span class="comment">BoyCoder</span></span><br><span class="line"><span class="comment">Thread:MySingleThread @coroutine#1</span></span><br><span class="line"><span class="comment">================================</span></span><br><span class="line"><span class="comment">*/</span></span><br></pre></td></tr></table></figure>

<p>在上面的代码中，我们是通过 asCoroutineDispatcher() 这个扩展函数，创建了一个 Dispatcher。从这里我们也能看到，Dispatcher 的本质仍然还是线程。这也再次验证了我们之前的说法：<strong>协程运行在线程之上</strong>。</p>
<p>然后在这里，当我们为 runBlocking 传入自定义的 mySingleDispatcher 以后，程序运行的结果就不一样了，由于它底层并没有复用线程，因此只有“In IO Context”是运行在 DefaultDispatcher 这个线程池的，其他代码都运行在 mySingleDispatcher 之上。</p>
<p>另外，前面提到的 <strong>Dispatchers.Unconfined</strong>，我们也要额外注意。还记得之前学习 launch 的时候，我们遇到的例子吗？请问下面 4 行代码，它们的执行顺序是怎样的？</p>
<figure class="highlight kotlin"><table><tr><td class="code"><pre><span class="line"></span><br><span class="line"><span class="comment">// 代码段7</span></span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">fun</span> <span class="title">main</span><span class="params">()</span></span> = runBlocking &#123;</span><br><span class="line">    logX(<span class="string">&quot;Before launch.&quot;</span>) <span class="comment">// 1</span></span><br><span class="line">    launch &#123;</span><br><span class="line">        logX(<span class="string">&quot;In launch.&quot;</span>) <span class="comment">// 2</span></span><br><span class="line">        delay(<span class="number">1000L</span>)</span><br><span class="line">        logX(<span class="string">&quot;End launch.&quot;</span>) <span class="comment">// 3</span></span><br><span class="line">    &#125;</span><br><span class="line">    logX(<span class="string">&quot;After launch&quot;</span>)   <span class="comment">// 4</span></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>如果你理解了第 14 讲的内容，那你一定能分析出它们的运行顺序应该是：1、4、2、3。</p>
<p>但你要注意，同样的代码模式在特殊的环境下，结果可能会不一样。比如在 Android 平台，或者是如果我们指定了 Dispatchers.Unconfined 这个特殊的 Dispatcher，它的这种行为模式也会被打破。比如像这样：</p>
<figure class="highlight kotlin"><table><tr><td class="code"><pre><span class="line"></span><br><span class="line"><span class="comment">// 代码段8</span></span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">fun</span> <span class="title">main</span><span class="params">()</span></span> = runBlocking &#123;</span><br><span class="line">    logX(<span class="string">&quot;Before launch.&quot;</span>)  <span class="comment">// 1</span></span><br><span class="line"><span class="comment">//               变化在这里</span></span><br><span class="line"><span class="comment">//                  ↓</span></span><br><span class="line">    launch(Dispatchers.Unconfined) &#123;</span><br><span class="line">        logX(<span class="string">&quot;In launch.&quot;</span>)  <span class="comment">// 2</span></span><br><span class="line">        delay(<span class="number">1000L</span>)</span><br><span class="line">        logX(<span class="string">&quot;End launch.&quot;</span>) <span class="comment">// 3</span></span><br><span class="line">    &#125;</span><br><span class="line">    logX(<span class="string">&quot;After launch&quot;</span>)    <span class="comment">// 4</span></span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">/*</span></span><br><span class="line"><span class="comment">输出结果：</span></span><br><span class="line"><span class="comment">================================</span></span><br><span class="line"><span class="comment">Before launch.</span></span><br><span class="line"><span class="comment">Thread:main @coroutine#1</span></span><br><span class="line"><span class="comment">================================</span></span><br><span class="line"><span class="comment">================================</span></span><br><span class="line"><span class="comment">In launch.</span></span><br><span class="line"><span class="comment">Thread:main @coroutine#2</span></span><br><span class="line"><span class="comment">================================</span></span><br><span class="line"><span class="comment">================================</span></span><br><span class="line"><span class="comment">After launch</span></span><br><span class="line"><span class="comment">Thread:main @coroutine#1</span></span><br><span class="line"><span class="comment">================================</span></span><br><span class="line"><span class="comment">================================</span></span><br><span class="line"><span class="comment">End launch.</span></span><br><span class="line"><span class="comment">Thread:kotlinx.coroutines.DefaultExecutor @coroutine#2</span></span><br><span class="line"><span class="comment">================================</span></span><br><span class="line"><span class="comment">*/</span></span><br></pre></td></tr></table></figure>

<p>以上代码的运行顺序就变成了：1、2、4、3。这一点，就再一次说明了 Kotlin 协程的难学。传了一个不同的参数进来，整个代码的执行顺序都变了，这谁不头疼呢？最要命的是，Dispatchers.Unconfined 设计的本意，也并不是用来改变代码执行顺序的。</p>
<p>请你留意“End launch”运行的线程“DefaultExecutor”，是不是觉得很乱？其实 Unconfined 代表的意思就是，<strong>当前协程可能运行在任何线程之上，不作强制要求</strong>。</p>
<p>由此可见，Dispatchers.Unconfined 其实是很危险的。<strong>所以，我们不应该随意使用 Dispatchers.Unconfined</strong>。</p>
<p>好，现在我们也了解了 CoroutineContext 的常见应用场景。不过，我们还没解释这节课的标题，什么是“万物皆为 Context”？</p>
<h2 id="万物皆有-Context"><a href="#万物皆有-Context" class="headerlink" title="万物皆有 Context"></a>万物皆有 Context</h2><p>所谓的“万物皆为 Context”，当然是一种夸张的说法，我们换成“万物皆有 Context”可能更加准确。</p>
<p>在 Kotlin 协程当中，但凡是重要的概念，都或多或少跟 CoroutineContext 有关系：Job、Dispatcher、CoroutineExceptionHandler、CoroutineScope，甚至挂起函数，它们都跟 CoroutineContext 有着密切的联系。甚至，它们之中的 Job、Dispatcher、CoroutineExceptionHandler 本身，就是 Context。</p>
<p>我这么一股脑地告诉你，你肯定觉得晕乎乎，所以下面我们就一个个来看。</p>
<h2 id="CoroutineScope"><a href="#CoroutineScope" class="headerlink" title="CoroutineScope"></a>CoroutineScope</h2><p>在学习 launch 的时候，我提到过如果要调用 launch，就必须先有“协程作用域”，也就是 CoroutineScope。</p>
<figure class="highlight kotlin"><table><tr><td class="code"><pre><span class="line"></span><br><span class="line"><span class="comment">// 代码段9</span></span><br><span class="line"></span><br><span class="line"><span class="comment">//            注意这里</span></span><br><span class="line"><span class="comment">//               ↓</span></span><br><span class="line"><span class="keyword">public</span> <span class="function"><span class="keyword">fun</span> CoroutineScope.<span class="title">launch</span><span class="params">(</span></span></span><br><span class="line"><span class="params"><span class="function">    context: <span class="type">CoroutineContext</span> = EmptyCoroutineContext,</span></span></span><br><span class="line"><span class="params"><span class="function">    start: <span class="type">CoroutineStart</span> = CoroutineStart.DEFAULT,</span></span></span><br><span class="line"><span class="params"><span class="function">    block: <span class="type">suspend</span> <span class="type">CoroutineScope</span>.() -&gt; <span class="type">Unit</span></span></span></span><br><span class="line"><span class="params"><span class="function">)</span></span>: Job &#123;&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">// CoroutineScope 源码</span></span><br><span class="line"><span class="keyword">public</span> <span class="keyword">interface</span> <span class="title class_">CoroutineScope</span> &#123;</span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">val</span> coroutineContext: CoroutineContext</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>如果你去看 CoroutineScope 的源码，你会发现，它其实就是一个简单的接口，而这个接口只有唯一的成员，就是 CoroutineContext。所以，CoroutineScope 只是对 CoroutineContext 做了一层封装而已，它的核心能力其实都来自于 CoroutineContext。</p>
<p>而 CoroutineScope 最大的作用，就是可以方便我们批量控制协程。</p>
<figure class="highlight kotlin"><table><tr><td class="code"><pre><span class="line"></span><br><span class="line"><span class="comment">// 代码段10</span></span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">fun</span> <span class="title">main</span><span class="params">()</span></span> = runBlocking &#123;</span><br><span class="line">    <span class="comment">// 仅用于测试，生成环境不要使用这么简易的CoroutineScope</span></span><br><span class="line">    <span class="keyword">val</span> scope = CoroutineScope(Job())</span><br><span class="line"></span><br><span class="line">    scope.launch &#123;</span><br><span class="line">        logX(<span class="string">&quot;First start!&quot;</span>)</span><br><span class="line">        delay(<span class="number">1000L</span>)</span><br><span class="line">        logX(<span class="string">&quot;First end!&quot;</span>) <span class="comment">// 不会执行</span></span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    scope.launch &#123;</span><br><span class="line">        logX(<span class="string">&quot;Second start!&quot;</span>)</span><br><span class="line">        delay(<span class="number">1000L</span>)</span><br><span class="line">        logX(<span class="string">&quot;Second end!&quot;</span>) <span class="comment">// 不会执行</span></span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    scope.launch &#123;</span><br><span class="line">        logX(<span class="string">&quot;Third start!&quot;</span>)</span><br><span class="line">        delay(<span class="number">1000L</span>)</span><br><span class="line">        logX(<span class="string">&quot;Third end!&quot;</span>) <span class="comment">// 不会执行</span></span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    delay(<span class="number">500L</span>)</span><br><span class="line"></span><br><span class="line">    scope.cancel()</span><br><span class="line"></span><br><span class="line">    delay(<span class="number">1000L</span>)</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">/*</span></span><br><span class="line"><span class="comment">输出结果：</span></span><br><span class="line"><span class="comment">================================</span></span><br><span class="line"><span class="comment">First start!</span></span><br><span class="line"><span class="comment">Thread:DefaultDispatcher-worker-1 @coroutine#2</span></span><br><span class="line"><span class="comment">================================</span></span><br><span class="line"><span class="comment">================================</span></span><br><span class="line"><span class="comment">Third start!</span></span><br><span class="line"><span class="comment">Thread:DefaultDispatcher-worker-3 @coroutine#4</span></span><br><span class="line"><span class="comment">================================</span></span><br><span class="line"><span class="comment">================================</span></span><br><span class="line"><span class="comment">Second start!</span></span><br><span class="line"><span class="comment">Thread:DefaultDispatcher-worker-2 @coroutine#3</span></span><br><span class="line"><span class="comment">================================</span></span><br><span class="line"><span class="comment">*/</span></span><br></pre></td></tr></table></figure>

<p>在上面的代码中，我们自己创建了一个简单的 CoroutineScope，接着，我们使用这个 scope 连续创建了三个协程，在 500 毫秒以后，我们就调用了 scope.cancel()，这样一来，代码中每个协程的“end”日志就不会输出了。</p>
<p>这同样体现了<strong>协程结构化并发</strong>的理念，相同的功能，我们借助 Job 也同样可以实现。关于 CoroutineScope 更多的底层细节，我们会在源码篇的时候深入学习。</p>
<p>那么接下来，我们就看看 Job 跟 CoroutineContext 的关系。</p>
<h2 id="Job-和-Dispatcher"><a href="#Job-和-Dispatcher" class="headerlink" title="Job 和 Dispatcher"></a>Job 和 Dispatcher</h2><p>如果说 CoroutineScope 是封装了 CoroutineContext，那么 Job 就是一个真正的 CoroutineContext 了。</p>
<figure class="highlight kotlin"><table><tr><td class="code"><pre><span class="line"></span><br><span class="line"><span class="comment">// 代码段11</span></span><br><span class="line"></span><br><span class="line"><span class="keyword">public</span> <span class="keyword">interface</span> <span class="title class_">Job</span> : <span class="type">CoroutineContext.Element</span> &#123;&#125;</span><br><span class="line"></span><br><span class="line"><span class="keyword">public</span> <span class="keyword">interface</span> <span class="title class_">CoroutineContext</span> &#123;</span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">interface</span> <span class="title class_">Element</span> : <span class="type">CoroutineContext</span> &#123;&#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>上面这段代码很有意思，Job 继承自 CoroutineContext.Element，而 CoroutineContext.Element 仍然继承自 CoroutineContext，这就意味着 Job 是间接继承自 CoroutineContext 的。所以说，Job 确实是一个真正的 CoroutineContext。</p>
<p>所以，我们写这样的代码也完全没问题：</p>
<figure class="highlight kotlin"><table><tr><td class="code"><pre><span class="line"></span><br><span class="line"><span class="comment">// 代码段12</span></span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">fun</span> <span class="title">main</span><span class="params">()</span></span> = runBlocking &#123;</span><br><span class="line">    <span class="keyword">val</span> job: CoroutineContext = Job()</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>不过，更有趣的是 CoroutineContext 本身的接口设计。</p>
<figure class="highlight kotlin"><table><tr><td class="code"><pre><span class="line"></span><br><span class="line"><span class="comment">// 代码段13</span></span><br><span class="line"></span><br><span class="line"><span class="keyword">public</span> <span class="keyword">interface</span> <span class="title class_">CoroutineContext</span> &#123;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">operator</span> <span class="function"><span class="keyword">fun</span> <span class="type">&lt;E : Element&gt;</span> <span class="title">get</span><span class="params">(key: <span class="type">Key</span>&lt;<span class="type">E</span>&gt;)</span></span>: E?</span><br><span class="line"></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">operator</span> <span class="function"><span class="keyword">fun</span> <span class="title">plus</span><span class="params">(context: <span class="type">CoroutineContext</span>)</span></span>: CoroutineContext &#123;&#125;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">public</span> <span class="function"><span class="keyword">fun</span> <span class="title">minusKey</span><span class="params">(key: <span class="type">Key</span>&lt;*&gt;)</span></span>: CoroutineContext</span><br><span class="line"></span><br><span class="line">    <span class="keyword">public</span> <span class="function"><span class="keyword">fun</span> <span class="type">&lt;R&gt;</span> <span class="title">fold</span><span class="params">(initial: <span class="type">R</span>, operation: (<span class="type">R</span>, <span class="type">Element</span>) -&gt; <span class="type">R</span>)</span></span>: R</span><br><span class="line"></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">interface</span> <span class="title class_">Key</span>&lt;<span class="type">E : Element</span>&gt;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>从上面代码中的 get()、plus()、minusKey()、fold() 这几个方法，我们可以看到 CoroutineContext 的接口设计，就跟集合 API 一样。准确来说，它的 API 设计和 Map 十分类似。</p>
<p><img src= "https://s2.loli.net/2023/03/09/dog2qQY83iTIvHM.gif" data-lazy-src="https://static001.geekbang.org/resource/image/a6/26/a611d29c307f953ebb099554a06a5d26.png?wh=1429x627" alt="img"></p>
<p>所以，我们完全可以<strong>把 CoroutineContext 当作 Map 来用</strong>。</p>
<figure class="highlight kotlin"><table><tr><td class="code"><pre><span class="line"></span><br><span class="line"><span class="comment">// 代码段14</span></span><br><span class="line"></span><br><span class="line"><span class="meta">@OptIn(ExperimentalStdlibApi::class)</span></span><br><span class="line"><span class="function"><span class="keyword">fun</span> <span class="title">main</span><span class="params">()</span></span> = runBlocking &#123;</span><br><span class="line">    <span class="comment">// 注意这里</span></span><br><span class="line">    <span class="keyword">val</span> scope = CoroutineScope(Job() + mySingleDispatcher)</span><br><span class="line"></span><br><span class="line">    scope.launch &#123;</span><br><span class="line">        <span class="comment">// 注意这里</span></span><br><span class="line">        logX(coroutineContext[CoroutineDispatcher] == mySingleDispatcher)</span><br><span class="line">        delay(<span class="number">1000L</span>)</span><br><span class="line">        logX(<span class="string">&quot;First end!&quot;</span>)  <span class="comment">// 不会执行</span></span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    delay(<span class="number">500L</span>)</span><br><span class="line">    scope.cancel()</span><br><span class="line">    delay(<span class="number">1000L</span>)</span><br><span class="line">&#125;</span><br><span class="line"><span class="comment">/*</span></span><br><span class="line"><span class="comment">输出结果：</span></span><br><span class="line"><span class="comment">================================</span></span><br><span class="line"><span class="comment">true</span></span><br><span class="line"><span class="comment">Thread:MySingleThread @coroutine#2</span></span><br><span class="line"><span class="comment">================================</span></span><br><span class="line"><span class="comment">*/</span></span><br></pre></td></tr></table></figure>

<p>在上面的代码中，我们使用了“Job() + mySingleDispatcher”这样的方式创建 CoroutineScope，代码之所以这么写，是因为 CoroutineContext 的 plus() 进行了<strong>操作符重载</strong>。</p>
<figure class="highlight kotlin"><table><tr><td class="code"><pre><span class="line"></span><br><span class="line"><span class="comment">// 代码段15</span></span><br><span class="line"></span><br><span class="line"><span class="comment">//     操作符重载</span></span><br><span class="line"><span class="comment">//        ↓</span></span><br><span class="line"><span class="keyword">public</span> <span class="keyword">operator</span> <span class="function"><span class="keyword">fun</span> <span class="type">&lt;E : Element&gt;</span> <span class="title">plus</span><span class="params">(key: <span class="type">Key</span>&lt;<span class="type">E</span>&gt;)</span></span>: E?</span><br></pre></td></tr></table></figure>

<p>你注意这里代码中的 <strong>operator 关键字</strong>，如果少了它，我们就得换一种方式了：mySingleDispatcher.plus(Job())。因为，当我们用 operator 修饰 plus() 方法以后，就可以用“+”来重载这个方法，类似的，List 和 Map 都支持这样的写法：list3 &#x3D; list1+list2、map3 &#x3D; map1 + map2，这代表集合之间的合并。</p>
<p>另外，我们还使用了“coroutineContext[CoroutineDispatcher]”这样的方式，访问当前协程所对应的 Dispatcher。这也是因为 CoroutineContext 的 get()，支持了<strong>操作符重载</strong>。</p>
<figure class="highlight kotlin"><table><tr><td class="code"><pre><span class="line"></span><br><span class="line"><span class="comment">// 代码段16</span></span><br><span class="line"></span><br><span class="line"><span class="comment">//     操作符重载</span></span><br><span class="line"><span class="comment">//        ↓</span></span><br><span class="line"><span class="keyword">public</span> <span class="keyword">operator</span> <span class="function"><span class="keyword">fun</span> <span class="type">&lt;E : Element&gt;</span> <span class="title">get</span><span class="params">(key: <span class="type">Key</span>&lt;<span class="type">E</span>&gt;)</span></span>: E?</span><br></pre></td></tr></table></figure>

<p>实际上，在 Kotlin 当中很多集合也是支持 get() 方法重载的，比如 List、Map，我们都可以使用这样的语法：list[0]、map[key]，以数组下标的方式来访问集合元素。</p>
<p>还记得我们在第 1 讲提到的“集合与数组的访问方式一致”这个知识点吗？现在我们知道了，这都要归功于操作符重载。实际上，Kotlin 官方的源代码当中大量使用了操作符重载来简化代码逻辑，而 CoroutineContext 就是一个最典型的例子。</p>
<p>如果你足够细心的话，这时候你应该也发现了：Dispatcher 本身也是 CoroutineContext，不然它怎么可以实现“Job() + mySingleDispatcher”这样的写法呢？最重要的是，当我们以这样的方式创建出 scope 以后，后续创建的协程就全部都运行在 mySingleDispatcher 这个线程之上了。</p>
<p>那么，<strong>Dispatcher 到底是如何跟 CoroutineContext 建立关系的呢？</strong>让我们来看看它的源码吧。</p>
<figure class="highlight kotlin"><table><tr><td class="code"><pre><span class="line"></span><br><span class="line"><span class="comment">// 代码段17</span></span><br><span class="line"></span><br><span class="line"><span class="keyword">public</span> <span class="keyword">actual</span> <span class="keyword">object</span> Dispatchers &#123;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">actual</span> <span class="keyword">val</span> Default: CoroutineDispatcher = DefaultScheduler</span><br><span class="line"></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">actual</span> <span class="keyword">val</span> Main: MainCoroutineDispatcher <span class="keyword">get</span>() = MainDispatcherLoader.dispatcher</span><br><span class="line"></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">actual</span> <span class="keyword">val</span> Unconfined: CoroutineDispatcher = kotlinx.coroutines.Unconfined</span><br><span class="line"></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">val</span> IO: CoroutineDispatcher = DefaultIoScheduler</span><br><span class="line"></span><br><span class="line">    <span class="keyword">public</span> <span class="function"><span class="keyword">fun</span> <span class="title">shutdown</span><span class="params">()</span></span> &#123;    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="keyword">public</span> <span class="keyword">abstract</span> <span class="keyword">class</span> <span class="title class_">CoroutineDispatcher</span> :</span><br><span class="line">    <span class="type">AbstractCoroutineContextElement</span>(ContinuationInterceptor), ContinuationInterceptor &#123;&#125;</span><br><span class="line"></span><br><span class="line"><span class="keyword">public</span> <span class="keyword">interface</span> <span class="title class_">ContinuationInterceptor</span> : <span class="type">CoroutineContext.Element</span> &#123;&#125;</span><br></pre></td></tr></table></figure>

<p>可以看到，Dispatchers 其实是一个 object 单例，它的内部成员的类型是 CoroutineDispatcher，而它又是继承自 ContinuationInterceptor，这个类则是实现了 CoroutineContext.Element 接口。由此可见，Dispatcher 确实就是 CoroutineContext</p>
<h2 id="其他-CoroutineContext"><a href="#其他-CoroutineContext" class="headerlink" title="其他 CoroutineContext"></a>其他 CoroutineContext</h2><p>除了上面几个重要的 CoroutineContext 之外，协程其实还有一些上下文是我们还没提到的。比如 CoroutineName，当我们创建协程的时候，可以传入指定的名称。比如：</p>
<figure class="highlight kotlin"><table><tr><td class="code"><pre><span class="line"></span><br><span class="line"><span class="comment">// 代码段18</span></span><br><span class="line"></span><br><span class="line"><span class="meta">@OptIn(ExperimentalStdlibApi::class)</span></span><br><span class="line"><span class="function"><span class="keyword">fun</span> <span class="title">main</span><span class="params">()</span></span> = runBlocking &#123;</span><br><span class="line">    <span class="keyword">val</span> scope = CoroutineScope(Job() + mySingleDispatcher)</span><br><span class="line">    <span class="comment">// 注意这里</span></span><br><span class="line">    scope.launch(CoroutineName(<span class="string">&quot;MyFirstCoroutine!&quot;</span>)) &#123;</span><br><span class="line">        logX(coroutineContext[CoroutineDispatcher] == mySingleDispatcher)</span><br><span class="line">        delay(<span class="number">1000L</span>)</span><br><span class="line">        logX(<span class="string">&quot;First end!&quot;</span>)</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    delay(<span class="number">500L</span>)</span><br><span class="line">    scope.cancel()</span><br><span class="line">    delay(<span class="number">1000L</span>)</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">/*</span></span><br><span class="line"><span class="comment">输出结果：</span></span><br><span class="line"><span class="comment"></span></span><br><span class="line"><span class="comment">================================</span></span><br><span class="line"><span class="comment">true</span></span><br><span class="line"><span class="comment">Thread:MySingleThread @MyFirstCoroutine!#2  // 注意这里</span></span><br><span class="line"><span class="comment">================================</span></span><br><span class="line"><span class="comment">*/</span></span><br></pre></td></tr></table></figure>

<p>在上面的代码中，我们调用 launch 的时候，传入了“CoroutineName(“MyFirstCoroutine!”)”作为协程的名字。在后面输出的结果中，我们得到了“@MyFirstCoroutine!#2”这样的输出。由此可见，其中的数字“2”，其实是一个自增的唯一 ID。</p>
<p>CoroutineContext 当中，还有一个重要成员是 <strong>CoroutineExceptionHandler</strong>，它主要负责处理协程当中的异常。</p>
<figure class="highlight kotlin"><table><tr><td class="code"><pre><span class="line"></span><br><span class="line"><span class="comment">// 代码段19</span></span><br><span class="line"></span><br><span class="line"><span class="keyword">public</span> <span class="keyword">interface</span> <span class="title class_">CoroutineExceptionHandler</span> : <span class="type">CoroutineContext.Element</span> &#123;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">companion</span> <span class="keyword">object</span> Key : CoroutineContext.Key&lt;CoroutineExceptionHandler&gt;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">public</span> <span class="function"><span class="keyword">fun</span> <span class="title">handleException</span><span class="params">(context: <span class="type">CoroutineContext</span>, exception: <span class="type">Throwable</span>)</span></span></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>可以看到，CoroutineExceptionHandler 的接口定义其实很简单，我们基本上一眼就能看懂。CoroutineExceptionHandler 真正重要的，其实只有 handleException() 这个方法，如果我们要自定义异常处理器，我们就只需要实现该方法即可。</p>
<figure class="highlight kotlin"><table><tr><td class="code"><pre><span class="line"></span><br><span class="line"><span class="comment">// 代码段20</span></span><br><span class="line"></span><br><span class="line"><span class="comment">//  这里使用了挂起函数版本的main()</span></span><br><span class="line"><span class="keyword">suspend</span> <span class="function"><span class="keyword">fun</span> <span class="title">main</span><span class="params">()</span></span> &#123;</span><br><span class="line">    <span class="keyword">val</span> myExceptionHandler = CoroutineExceptionHandler &#123; _, throwable -&gt;</span><br><span class="line">        println(<span class="string">&quot;Catch exception: <span class="variable">$throwable</span>&quot;</span>)</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">val</span> scope = CoroutineScope(Job() + mySingleDispatcher)</span><br><span class="line"></span><br><span class="line">    <span class="keyword">val</span> job = scope.launch(myExceptionHandler) &#123;</span><br><span class="line">        <span class="keyword">val</span> s: String? = <span class="literal">null</span></span><br><span class="line">        s!!.length <span class="comment">// 空指针异常</span></span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    job.join()</span><br><span class="line">&#125;</span><br><span class="line"><span class="comment">/*</span></span><br><span class="line"><span class="comment">输出结果：</span></span><br><span class="line"><span class="comment">Catch exception: java.lang.NullPointerException</span></span><br><span class="line"><span class="comment">*/</span></span><br></pre></td></tr></table></figure>

<p>不过，虽然 CoroutineExceptionHandler 的用法看起来很简单，但当它跟协程“结构化并发”理念相结合以后，内部的异常处理逻辑是很复杂的。关于协程异常处理的机制，我们会在第 23 讲详细介绍。</p>
<h2 id="小结"><a href="#小结" class="headerlink" title="小结"></a>小结</h2><p>这节课的内容到这里就结束了，我们来总结一下吧。</p>
<ul>
<li>CoroutineContext，是 Kotlin 协程当中非常关键的一个概念。它本身是一个接口，但它的接口设计与 Map 的 API 极为相似，我们在使用的过程中，也可以<strong>把它当作 Map 来用</strong>。</li>
<li>协程里很多重要的类，它们本身都是 CoroutineContext。比如 Job、Deferred、Dispatcher、ContinuationInterceptor、CoroutineName、CoroutineExceptionHandler，它们都继承自 CoroutineContext 这个接口。也正因为它们都继承了 CoroutineContext 接口，所以我们可以通过<strong>操作符重载</strong>的方式，写出更加灵活的代码，比如“Job() + mySingleDispatcher+CoroutineName(“MyFirstCoroutine!”)”。</li>
<li>协程当中的 CoroutineScope，本质上也是 CoroutineContext 的一层<strong>简单封装</strong>。</li>
<li>另外，协程里极其重要的“挂起函数”，它与 CoroutineContext 之间也有着非常紧密的联系。</li>
</ul>
<p>另外我也画了一张结构图，来描述 CoroutineContext 元素之间的关系，方便你建立完整的知识体系。</p>
<p><img src= "https://s2.loli.net/2023/03/09/dog2qQY83iTIvHM.gif" data-lazy-src="https://static001.geekbang.org/resource/image/eb/76/eb225787718e0d2cff8a55bcba86yy76.jpg?wh=2000x1125" alt="img"></p>
<p>所以总的来说，我们前面学习的 Job、Dispatcher、CoroutineName，它们本质上只是 CoroutieContext 这个集合当中的一种数据类型，只是恰好 Kotlin 官方让它们都继承了 CoroutineContext 这个接口。而 CoroutineScope 则是对 CoroutineContext 的进一步封装，它的核心能力，全部都是源自于 CoroutineContext。</p>
<h2 id="思考题"><a href="#思考题" class="headerlink" title="思考题"></a>思考题</h2><p>课程里，我提到了“挂起函数”与 CoroutineContext 也有着紧密的联系，请问，你能找到具体的证据吗？或者，你觉得下面的代码能成功运行吗？为什么？</p>
<figure class="highlight kotlin"><table><tr><td class="code"><pre><span class="line"></span><br><span class="line"><span class="comment">// 代码段21</span></span><br><span class="line"></span><br><span class="line"><span class="keyword">import</span> kotlinx.coroutines.*</span><br><span class="line"><span class="keyword">import</span> kotlin.coroutines.coroutineContext</span><br><span class="line"></span><br><span class="line"><span class="comment">//                        挂起函数能可以访问协程上下文吗？</span></span><br><span class="line"><span class="comment">//                                 ↓                              </span></span><br><span class="line"><span class="keyword">suspend</span> <span class="function"><span class="keyword">fun</span> <span class="title">testContext</span><span class="params">()</span></span> = coroutineContext</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">fun</span> <span class="title">main</span><span class="params">()</span></span> = runBlocking &#123;</span><br><span class="line">    println(testContext())</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

</article><div class="post-copyright"><div class="post-copyright__author"><span class="post-copyright-meta">文章作者: </span><span class="post-copyright-info"><a href="https://devsu.top">Carl Su</a></span></div><div class="post-copyright__type"><span class="post-copyright-meta">文章链接: </span><span class="post-copyright-info"><a href="https://devsu.top/posts/12ca5097/">https://devsu.top/posts/12ca5097/</a></span></div><div class="post-copyright__notice"><span class="post-copyright-meta">版权声明: </span><span class="post-copyright-info">本博客所有文章除特别声明外，均采用 <a href="https://creativecommons.org/licenses/by-nc-sa/4.0/" target="_blank">CC BY-NC-SA 4.0</a> 许可协议。转载请注明来自 <a href="https://devsu.top" target="_blank">码行</a>！</span></div></div><div class="tag_share"><div class="post-meta__tag-list"><a class="post-meta__tags" href="/tags/Kotlin/">Kotlin</a></div><div class="post_share"><div class="social-share" data-image="https://img2.baidu.com/it/u=3107178066,1951512797&amp;fm=253&amp;fmt=auto&amp;app=138&amp;f=JPEG?w=704&amp;h=500" data-sites="facebook,twitter,wechat,weibo,qq"></div><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/butterfly-extsrc/sharejs/dist/css/share.min.css" media="print" onload="this.media='all'"><script src="https://cdn.jsdelivr.net/npm/butterfly-extsrc/sharejs/dist/js/social-share.min.js" defer></script></div></div><nav class="pagination-post" id="pagination"><div class="prev-post pull-left"><a href="/posts/95448d7b/" title="Kotlin编程第一课--(协程篇)18  实战：让KtHttp支持挂起函数"><img class="cover" src="https://img0.baidu.com/it/u=4294224436,2248563340&amp;fm=253&amp;fmt=auto&amp;app=120&amp;f=JPEG?w=1280&amp;h=800" onerror="onerror=null;src='/img/404.jpg'" alt="cover of previous post"><div class="pagination-info"><div class="label">上一篇</div><div class="prev_info">Kotlin编程第一课--(协程篇)18  实战：让KtHttp支持挂起函数</div></div></a></div><div class="next-post pull-right"><a href="/posts/5b46e6ea/" title="Kotlin编程第一课--(协程篇)16  Job：协程也有生命周期吗？"><img class="cover" src="https://img1.baidu.com/it/u=1052255644,1248205582&amp;fm=253&amp;fmt=auto&amp;app=120&amp;f=JPEG?w=1280&amp;h=800" onerror="onerror=null;src='/img/404.jpg'" alt="cover of next post"><div class="pagination-info"><div class="label">下一篇</div><div class="next_info">Kotlin编程第一课--(协程篇)16  Job：协程也有生命周期吗？</div></div></a></div></nav><div class="relatedPosts"><div class="headline"><i class="fas fa-thumbs-up fa-fw"></i><span>相关推荐</span></div><div class="relatedPosts-list"><div><a href="/posts/85d82fa8/" title="Kotlin编程第一课--(基础篇)06  扩展：你的能力边界到底在哪里？"><img class="cover" src="https://static001.geekbang.org/resource/image/b6/1c/b65feyy0bdc4764c6564a95912d7851c.jpg" alt="cover"><div class="content is-center"><div class="date"><i class="far fa-calendar-alt fa-fw"></i> 2022-05-06</div><div class="title">Kotlin编程第一课--(基础篇)06  扩展：你的能力边界到底在哪里？</div></div></a></div><div><a href="/posts/be9f17d6/" title="Kotlin编程第一课(目录)"><img class="cover" src="https://img2.baidu.com/it/u=3956021957,3313212296&fm=253&fmt=auto&app=138&f=JPEG?w=800&h=500" alt="cover"><div class="content is-center"><div class="date"><i class="far fa-calendar-alt fa-fw"></i> 2022-07-10</div><div class="title">Kotlin编程第一课(目录)</div></div></a></div><div><a href="/posts/83a7144c/" title="2023-01-17-Kotlin协程 -  结构化并发"><img class="cover" src="https://s2.loli.net/2023/03/14/xEyFgn24zZPXe15.jpg" alt="cover"><div class="content is-center"><div class="date"><i class="far fa-calendar-alt fa-fw"></i> 2023-01-17</div><div class="title">2023-01-17-Kotlin协程 -  结构化并发</div></div></a></div><div><a href="/posts/68bf7d20/" title="Kotlin函数"><img class="cover" src="https://img1.baidu.com/it/u=1546227440,2897989905&fm=253&fmt=auto&app=138&f=JPEG?w=889&h=500" alt="cover"><div class="content is-center"><div class="date"><i class="far fa-calendar-alt fa-fw"></i> 2022-08-05</div><div class="title">Kotlin函数</div></div></a></div><div><a href="/posts/a20c9e06/" title="Kotlin协程"><img class="cover" src="https://s2.loli.net/2023/03/14/3MHPBy1Q4GncRlF.png" alt="cover"><div class="content is-center"><div class="date"><i class="far fa-calendar-alt fa-fw"></i> 2023-02-09</div><div class="title">Kotlin协程</div></div></a></div><div><a href="/posts/8c331668/" title="Kotlin内置函数apply、let、run、with、also等区别"><img class="cover" src="https://s2.loli.net/2023/03/14/OpxWcuy2ktMzoQD.jpg" alt="cover"><div class="content is-center"><div class="date"><i class="far fa-calendar-alt fa-fw"></i> 2022-08-05</div><div class="title">Kotlin内置函数apply、let、run、with、also等区别</div></div></a></div></div></div><hr/><div id="post-comment"><div class="comment-head"><div class="comment-headline"><i class="fas fa-comments fa-fw"></i><span> 评论</span></div><div id="comment-switch"><span class="first-comment">Valine</span><span class="switch-btn"></span><span class="second-comment">Disqus</span></div></div><div class="comment-wrap"><div><div class="vcomment" id="vcomment"></div></div><div><div id="disqus_thread"></div></div></div></div></div><div class="aside-content" id="aside-content"><div class="sticky_layout"><div class="card-widget" id="card-toc"><div class="item-headline"><i class="fas fa-stream"></i><span>目录</span><span class="toc-percentage"></span></div><div class="toc-content"><ol class="toc"><li class="toc-item toc-level-2"><a class="toc-link" href="#Context-%E7%9A%84%E5%BA%94%E7%94%A8"><span class="toc-number">1.</span> <span class="toc-text">Context 的应用</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E4%B8%87%E7%89%A9%E7%9A%86%E6%9C%89-Context"><span class="toc-number">2.</span> <span class="toc-text">万物皆有 Context</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#CoroutineScope"><span class="toc-number">3.</span> <span class="toc-text">CoroutineScope</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#Job-%E5%92%8C-Dispatcher"><span class="toc-number">4.</span> <span class="toc-text">Job 和 Dispatcher</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E5%85%B6%E4%BB%96-CoroutineContext"><span class="toc-number">5.</span> <span class="toc-text">其他 CoroutineContext</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E5%B0%8F%E7%BB%93"><span class="toc-number">6.</span> <span class="toc-text">小结</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E6%80%9D%E8%80%83%E9%A2%98"><span class="toc-number">7.</span> <span class="toc-text">思考题</span></a></li></ol></div></div></div></div></main><footer id="footer"><div id="footer-wrap"><div class="copyright">&copy;2018 - 2023 By Carl Su</div><div class="framework-info"><span>框架 </span><a target="_blank" rel="noopener" href="https://hexo.io">Hexo</a><span class="footer-separator">|</span><span>主题 </span><a target="_blank" rel="noopener" href="https://github.com/jerryc127/hexo-theme-butterfly">Butterfly</a></div><div class="footer_custom_text">学无止境</div></div></footer></div><div id="rightside"><div id="rightside-config-hide"><button id="readmode" type="button" title="阅读模式"><i class="fas fa-book-open"></i></button><button id="translateLink" type="button" title="简繁转换">繁</button><button id="darkmode" type="button" title="浅色和深色模式转换"><i class="fas fa-adjust"></i></button><button id="hide-aside-btn" type="button" title="单栏和双栏切换"><i class="fas fa-arrows-alt-h"></i></button></div><div id="rightside-config-show"><button id="rightside_config" type="button" title="设置"><i class="fas fa-cog fa-spin"></i></button><button class="close" id="mobile-toc-button" type="button" title="目录"><i class="fas fa-list-ul"></i></button><button id="chat_btn" type="button" title="聊天"><i class="fas fa-sms"></i></button><a id="to_comment" href="#post-comment" title="直达评论"><i class="fas fa-comments"></i></a><button id="go-up" type="button" title="回到顶部"><span class="scroll-percent"></span><i class="fas fa-arrow-up"></i></button></div></div><div><script src="/js/utils.js"></script><script src="/js/main.js"></script><script src="/js/tw_cn.js"></script><script src="https://cdn.jsdelivr.net/npm/@fancyapps/ui/dist/fancybox.umd.min.js"></script><script src="https://cdn.jsdelivr.net/npm/vanilla-lazyload/dist/lazyload.iife.min.js"></script><script src="https://cdn.jsdelivr.net/npm/node-snackbar/dist/snackbar.min.js"></script><div class="js-pjax"><script>function loadValine () {
  function initValine () {
    const valine = new Valine(Object.assign({
      el: '#vcomment',
      appId: '',
      appKey: '',
      avatar: 'monsterid',
      serverURLs: '',
      emojiMaps: "",
      path: window.location.pathname,
      visitor: false
    }, null))
  }

  if (typeof Valine === 'function') initValine() 
  else getScript('https://cdn.jsdelivr.net/npm/valine/dist/Valine.min.js').then(initValine)
}

if ('Valine' === 'Valine' || !true) {
  if (true) btf.loadComment(document.getElementById('vcomment'),loadValine)
  else setTimeout(loadValine, 0)
} else {
  function loadOtherComment () {
    loadValine()
  }
}</script><script>function loadDisqus () {
  var disqus_config = function () {
    this.page.url = 'https://devsu.top/posts/12ca5097/'
    this.page.identifier = '/posts/12ca5097/'
    this.page.title = 'Kotlin编程第一课--(协程篇)17  Context：万物皆为Context？'
  };

  window.disqusReset = () => {
    DISQUS.reset({
      reload: true,
      config: disqus_config
    })
  }

  if (window.DISQUS) disqusReset()
  else {
    (function() { 
      var d = document, s = d.createElement('script');
      s.src = 'https://.disqus.com/embed.js';
      s.setAttribute('data-timestamp', +new Date());
      (d.head || d.body).appendChild(s);
    })();
  }

  document.getElementById('darkmode').addEventListener('click', () => {
    setTimeout(() => window.disqusReset(), 200)
  })
}

if ('Valine' === 'Disqus' || !true) {
  if (true) btf.loadComment(document.getElementById('disqus_thread'), loadDisqus)
  else loadDisqus()
} else {
  function loadOtherComment () {
    loadDisqus()
  }
}
</script></div><script defer="defer" id="fluttering_ribbon" mobile="false" src="https://cdn.jsdelivr.net/npm/butterfly-extsrc/dist/canvas-fluttering-ribbon.min.js"></script><script src="https://cdn.jsdelivr.net/npm/butterfly-extsrc/dist/activate-power-mode.min.js"></script><script>POWERMODE.colorful = true;
POWERMODE.shake = false;
POWERMODE.mobile = false;
document.body.addEventListener('input', POWERMODE);
</script><script id="click-heart" src="https://cdn.jsdelivr.net/npm/butterfly-extsrc/dist/click-heart.min.js" async="async" mobile="false"></script><script async data-pjax src="//busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script></div><div id="local-search"><div class="search-dialog"><nav class="search-nav"><span class="search-dialog-title">搜索</span><span id="loading-status"></span><button class="search-close-button"><i class="fas fa-times"></i></button></nav><div class="is-center" id="loading-database"><i class="fas fa-spinner fa-pulse"></i><span>  数据库加载中</span></div><div class="search-wrap"><div id="local-search-input"><div class="local-search-box"><input class="local-search-box--input" placeholder="搜索文章" type="text"/></div></div><hr/><div id="local-search-results"></div></div></div><div id="search-mask"></div><script src="/js/search/local-search.js"></script></div></body></html>